package com.example.springboot.common.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.resp.Result;
import com.example.springboot.common.utils.JWTUtils;
import com.example.springboot.system.entity.RoleEntity;
import com.example.springboot.system.entity.SaleEntity;
import com.example.springboot.system.entity.StaffEntity;
import com.example.springboot.system.entity.UserEntity;
import com.example.springboot.system.mapper.StaffMapper;
import com.example.springboot.system.service.StaffService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@Tag(name = "登录")
@RestController
public class LoginController {

    @Autowired
    private StaffService staffService;

    @Operation(summary = "登录")
    @PostMapping("/login")
    public Result<?> login(@RequestParam String acc, @RequestParam String pwd, @RequestParam String code, HttpSession session) {
        //验证码比对
        if (!session.getAttribute("code").equals(code)) {
            return Result.failure("验证码错误");
        }
        //获取个人信息
        QueryWrapper<StaffEntity> wrapperUser = new QueryWrapper<>();
        wrapperUser.eq("staff_acc", acc);
        StaffEntity staff = staffService.getOne(wrapperUser);
        //账号存在性
        if (staff == null) return Result.failure("账号不存在，登陆失败");
        //账号是否正常
        if (staff.getState() == 0 || staff.getUndock() == 1) return Result.failure("账号状态异常，请联系管理员处理");
        //密码比对
        if (!pwd.equals(staff.getPwd())) return Result.failure("密码错误，登陆失败");
        //生成token
        HashMap<String, String> map = new HashMap<>();
        map.put("name", staff.getName());
        map.put("acc", staff.getAcc());
        map.put("pwd", staff.getPwd());
        String token = JWTUtils.generateToken(map);
        //返回数据
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token", token);
        hashMap.put("user", staff);
        return Result.success("登录成功", hashMap);
    }

}
